package cn.com.nes.common.util;

import cn.com.nes.common.packet.AbstractPacket;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoPool;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.util.List;

import static io.netty.buffer.Unpooled.wrappedBuffer;

public class KryoEncoder extends MessageToMessageEncoder<AbstractPacket> {

    private final KryoPool kryoPool;

    public KryoEncoder(KryoPool kryoPool) {
        if (kryoPool == null) {
            throw new NullPointerException("kryoPool");
        }
        this.kryoPool = kryoPool;
    }

    public KryoEncoder() {
        this(KryoUtil.newKryoPool());
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, AbstractPacket msg, List<Object> out) throws Exception {
        Kryo kryo = null;
        try {
            kryo = kryoPool.borrow();
            Output output = new Output(1024, -1);
            kryo.writeClassAndObject(output, msg);
            out.add(wrappedBuffer(output.getBuffer(), 0, output.position()));
        } finally {
            if(kryo != null) {
                kryoPool.release(kryo);
            }
        }
    }

}
